import { ILogin, IMainApiAuth, IRegister } from '../interfaces'

class MainApiAuth implements IMainApiAuth {
  baseUrl: string
  headers: any
  constructor({ baseUrl, headers }) {
    this.baseUrl = baseUrl;
    this.headers = headers;
  }

   private _checkResponse = (res: any) => {
    if (res.ok) {
      return res.json();
    }
    return Promise.reject(`Ой...: ${res.status}`);
  }

  private async _request(url: string, options: any) {
    const res = await fetch(url, options);
    return this._checkResponse(res);
  }

  checkToken(token: string): Promise<any> {
    return this._request(`${this.baseUrl}/users/me`, {
      headers: { ...this.headers, Authorization: `Bearer ${token}` },
    });
  }

  signup(registerData: IRegister): Promise<any> {
    const { name, email, password } = registerData
    return this._request(`${this.baseUrl}/signup`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify({
        name: name,
        email: email,
        password: password,
        accessLevel: 'usual'
      }),
    });
  }

  signin(loginData: ILogin) {
    const { email, password } = loginData
    return this._request(`${this.baseUrl}/signin`, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify({
        password: password,
        email: email,
      }),
    });
  }
}

export const mainApiAuth = new MainApiAuth({
  // baseUrl: `https://api.movies-diplom.nomoredomainsicu.ru`,
  baseUrl: `http://localhost:3000`,
  headers: {
    'Content-Type': 'application/json',
  },
});
